package com.test.springmybatis;

import java.lang.reflect.Field;

import lombok.Getter;
import sun.misc.Unsafe;

@Getter
public class UnsafeOperations {
    private static final Unsafe UNSAFE;
    private static final long FIELD_OFFSET;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
            FIELD_OFFSET = UNSAFE.objectFieldOffset
                    (UnsafeOperations.class.getDeclaredField("value"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    private volatile int value;

    public UnsafeOperations(int initialValue) {
        value = initialValue;
    }

    public void setValueUsingUnsafe(int newValue) {
        UNSAFE.putOrderedInt(this, FIELD_OFFSET, newValue);
    }

    public static void main(String[] args) {
        UnsafeOperations ops = new UnsafeOperations(10);
        System.out.println("Initial value: " + ops.getValue());
        ops.setValueUsingUnsafe(20);
        System.out.println("New value: " + ops.getValue());
    }
}
